home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Resources / Chat & Communication / Digsby build 37 / digsby_setup.exe / lib / ZSI / client.pyo (.txt) < prev    next >
Python Compiled Bytecode  |  2008-10-13  |  16KB  |  488 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.5)
  3.  
  4. from ZSI import _copyright, _seqtypes, ParsedSoap, SoapWriter, TC, ZSI_SCHEMA_URI, EvaluateException, FaultFromFaultMessage, _child_elements, _attrs, _find_arraytype, _find_type, _get_idstr, _get_postvalue_from_absoluteURI, FaultException, WSActionException, UNICODE_ENCODING
  5. from ZSI.auth import AUTH
  6. from ZSI.TC import AnyElement, AnyType, String, TypeCode, _get_global_element_declaration, _get_type_definition
  7. from ZSI.TCcompound import Struct
  8. import base64
  9. import httplib
  10. import Cookie
  11. import types
  12. import time
  13. import urlparse
  14. from ZSI.address import Address
  15. from ZSI.wstools.logging import getLogger as _GetLogger
  16. _b64_encode = base64.encodestring
  17.  
  18. class _AuthHeader:
  19.     
  20.     def __init__(self, name = None, password = None):
  21.         self.Name = name
  22.         self.Password = password
  23.  
  24.  
  25. _AuthHeader.typecode = Struct(_AuthHeader, ofwhat = (String((ZSI_SCHEMA_URI, 'Name'), typed = False), String((ZSI_SCHEMA_URI, 'Password'), typed = False)), pname = (ZSI_SCHEMA_URI, 'BasicAuth'), typed = False)
  26.  
  27. class _Caller:
  28.     
  29.     def __init__(self, binding, name, namespace = None):
  30.         self.binding = binding
  31.         self.name = name
  32.         self.namespace = namespace
  33.  
  34.     
  35.     def __call__(self, *args):
  36.         nsuri = self.namespace
  37.         if nsuri is None:
  38.             return self.binding.RPC(None, self.name, args, encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/', replytype = TC.Any(self.name + 'Response'))
  39.         
  40.         return self.binding.RPC(None, (nsuri, self.name), args, encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/', replytype = TC.Any((nsuri, self.name + 'Response')))
  41.  
  42.  
  43.  
  44. class _NamedParamCaller:
  45.     
  46.     def __init__(self, binding, name, namespace = None):
  47.         self.binding = binding
  48.         self.name = name
  49.         self.namespace = namespace
  50.  
  51.     
  52.     def __call__(self, **params):
  53.         kw = { }
  54.         for key in [
  55.             'auth_header',
  56.             'nsdict',
  57.             'requesttypecode',
  58.             'soapaction']:
  59.             if params.has_key(key):
  60.                 kw[key] = params[key]
  61.                 del params[key]
  62.                 continue
  63.         
  64.         nsuri = self.namespace
  65.         if nsuri is None:
  66.             return self.binding.RPC(None, self.name, None, encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/', _args = params, replytype = TC.Any(self.name + 'Response', aslist = False), **kw)
  67.         
  68.         return self.binding.RPC(None, (nsuri, self.name), None, encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/', _args = params, replytype = TC.Any((nsuri, self.name + 'Response'), aslist = False), **kw)
  69.  
  70.  
  71.  
  72. class _Binding:
  73.     defaultHttpTransport = httplib.HTTPConnection
  74.     defaultHttpsTransport = httplib.HTTPSConnection
  75.     logger = _GetLogger('ZSI.client.Binding')
  76.     
  77.     def __init__(self, nsdict = None, transport = None, url = None, tracefile = None, readerclass = None, writerclass = None, soapaction = '', wsAddressURI = None, sig_handler = None, transdict = None, **kw):
  78.         self.data = None
  79.         self.ps = None
  80.         self.user_headers = []
  81.         if not nsdict:
  82.             pass
  83.         self.nsdict = { }
  84.         self.transport = transport
  85.         if not transdict:
  86.             pass
  87.         self.transdict = { }
  88.         self.url = url
  89.         self.trace = tracefile
  90.         self.readerclass = readerclass
  91.         self.writerclass = writerclass
  92.         self.soapaction = soapaction
  93.         self.wsAddressURI = wsAddressURI
  94.         self.sig_handler = sig_handler
  95.         self.address = None
  96.         self.endPointReference = kw.get('endPointReference', None)
  97.         self.cookies = Cookie.SimpleCookie()
  98.         self.http_callbacks = { }
  99.         if kw.has_key('auth'):
  100.             self.SetAuth(*kw['auth'])
  101.         else:
  102.             self.SetAuth(AUTH.none)
  103.  
  104.     
  105.     def SetAuth(self, style, user = None, password = None):
  106.         self.auth_style = style
  107.         self.auth_user = user
  108.         self.auth_pass = password
  109.         return self
  110.  
  111.     
  112.     def SetURL(self, url):
  113.         self.url = url
  114.         return self
  115.  
  116.     
  117.     def ResetHeaders(self):
  118.         self.user_headers = []
  119.         return self
  120.  
  121.     
  122.     def ResetCookies(self):
  123.         self.cookies = Cookie.SimpleCookie()
  124.  
  125.     
  126.     def AddHeader(self, header, value):
  127.         self.user_headers.append((header, value))
  128.         return self
  129.  
  130.     
  131.     def _Binding__addcookies(self):
  132.         for cname, morsel in self.cookies.items():
  133.             attrs = []
  134.             value = morsel.get('version', '')
  135.             if value != '' and value != '0':
  136.                 attrs.append('$Version=%s' % value)
  137.             
  138.             attrs.append('%s=%s' % (cname, morsel.coded_value))
  139.             value = morsel.get('path')
  140.             if value:
  141.                 attrs.append('$Path=%s' % value)
  142.             
  143.             value = morsel.get('domain')
  144.             if value:
  145.                 attrs.append('$Domain=%s' % value)
  146.             
  147.             self.h.putheader('Cookie', '; '.join(attrs))
  148.         
  149.  
  150.     
  151.     def RPC(self, url, opname, obj, replytype = None, **kw):
  152.         self.Send(url, opname, obj, **kw)
  153.         return self.Receive(replytype, **kw)
  154.  
  155.     
  156.     def Send(self, url, opname, obj, nsdict = { }, soapaction = None, wsaction = None, endPointReference = None, soapheaders = (), **kw):
  157.         if not url:
  158.             pass
  159.         url = self.url
  160.         if not endPointReference:
  161.             pass
  162.         endPointReference = self.endPointReference
  163.         d = { }
  164.         d.update(self.nsdict)
  165.         d.update(nsdict)
  166.         sw = SoapWriter(nsdict = d, header = True, outputclass = self.writerclass, encodingStyle = kw.get('encodingStyle'))
  167.         requesttypecode = kw.get('requesttypecode')
  168.         if kw.has_key('_args'):
  169.             if not requesttypecode:
  170.                 pass
  171.             tc = TC.Any(pname = opname, aslist = False)
  172.             sw.serialize(kw['_args'], tc)
  173.         elif not requesttypecode:
  174.             if not getattr(obj, 'typecode', None):
  175.                 pass
  176.             tc = TC.Any(pname = opname, aslist = False)
  177.             
  178.             try:
  179.                 if type(obj) in _seqtypes:
  180.                     obj = dict(map((lambda i: (i.typecode.pname, i)), obj))
  181.             except AttributeError:
  182.                 tc = TC.Any(pname = opname, aslist = True)
  183.  
  184.             tc = TC.Any(pname = opname, aslist = False)
  185.             sw.serialize(obj, tc)
  186.         else:
  187.             sw.serialize(obj, requesttypecode)
  188.         for i in soapheaders:
  189.             sw.serialize_header(i)
  190.         
  191.         if self.auth_style & AUTH.zsibasic:
  192.             sw.serialize_header(_AuthHeader(self.auth_user, self.auth_pass), _AuthHeader.typecode)
  193.         
  194.         if self.wsAddressURI is not None:
  195.             if self.soapaction and wsaction.strip('\'"') != self.soapaction:
  196.                 raise WSActionException, 'soapAction(%s) and WS-Action(%s) must match' % (self.soapaction, wsaction)
  197.             
  198.             self.address = Address(url, self.wsAddressURI)
  199.             self.address.setRequest(endPointReference, wsaction)
  200.             self.address.serialize(sw)
  201.         
  202.         if self.sig_handler is not None:
  203.             self.sig_handler.sign(sw)
  204.         
  205.         (scheme, netloc, path, nil, nil, nil) = urlparse.urlparse(url)
  206.         transport = self.transport
  207.         if transport is None and url is not None:
  208.             if scheme == 'https':
  209.                 transport = self.defaultHttpsTransport
  210.             elif scheme == 'http':
  211.                 transport = self.defaultHttpTransport
  212.             else:
  213.                 raise RuntimeError, 'must specify transport or url startswith https/http'
  214.         
  215.         if issubclass(transport, httplib.HTTPConnection) is False:
  216.             raise TypeError, 'transport must be a HTTPConnection'
  217.         
  218.         soapdata = str(sw)
  219.         self.h = transport(netloc, None, **self.transdict)
  220.         self.h.connect()
  221.         self.SendSOAPData(soapdata, url, soapaction, **kw)
  222.  
  223.     
  224.     def SendSOAPData(self, soapdata, url, soapaction, headers = { }, **kw):
  225.         if self.trace:
  226.             print >>self.trace, '_' * 33, time.ctime(time.time()), 'REQUEST:'
  227.             print >>self.trace, soapdata
  228.         
  229.         if not url:
  230.             pass
  231.         url = self.url
  232.         request_uri = _get_postvalue_from_absoluteURI(url)
  233.         self.h.putrequest('POST', request_uri)
  234.         self.h.putheader('Content-Length', '%d' % len(soapdata))
  235.         self.h.putheader('Content-Type', 'text/xml; charset="%s"' % UNICODE_ENCODING)
  236.         self._Binding__addcookies()
  237.         for header, value in headers.items():
  238.             self.h.putheader(header, value)
  239.         
  240.         if not soapaction:
  241.             pass
  242.         SOAPActionValue = '"%s"' % self.soapaction
  243.         self.h.putheader('SOAPAction', SOAPActionValue)
  244.         if self.auth_style & AUTH.httpbasic:
  245.             val = _b64_encode(self.auth_user + ':' + self.auth_pass).replace('\n', '')
  246.             self.h.putheader('Authorization', 'Basic ' + val)
  247.         elif self.auth_style == AUTH.httpdigest and not headers.has_key('Authorization') and not headers.has_key('Expect'):
  248.             
  249.             def digest_auth_cb(response):
  250.                 self.SendSOAPDataHTTPDigestAuth(response, soapdata, url, request_uri, soapaction, **kw)
  251.                 self.http_callbacks[401] = None
  252.  
  253.             self.http_callbacks[401] = digest_auth_cb
  254.         
  255.         for header, value in self.user_headers:
  256.             self.h.putheader(header, value)
  257.         
  258.         self.h.endheaders()
  259.         self.h.send(soapdata)
  260.         (self.data, self.ps) = (None, None)
  261.  
  262.     
  263.     def SendSOAPDataHTTPDigestAuth(self, response, soapdata, url, request_uri, soapaction, **kw):
  264.         if self.trace:
  265.             print >>self.trace, '------ Digest Auth Header'
  266.         
  267.         if not url:
  268.             pass
  269.         url = self.url
  270.         if response.status != 401:
  271.             raise RuntimeError, 'Expecting HTTP 401 response.'
  272.         
  273.         if self.auth_style != AUTH.httpdigest:
  274.             raise RuntimeError, 'Auth style(%d) does not support requested digest authorization.' % self.auth_style
  275.         
  276.         fetch_challenge = fetch_challenge
  277.         generate_response = generate_response
  278.         build_authorization_arg = build_authorization_arg
  279.         dict_fetch = dict_fetch
  280.         import ZSI.digest_auth
  281.         chaldict = fetch_challenge(response.getheader('www-authenticate'))
  282.         if dict_fetch(chaldict, 'challenge', '').lower() == 'digest' and dict_fetch(chaldict, 'nonce', None) and dict_fetch(chaldict, 'realm', None) and dict_fetch(chaldict, 'qop', None):
  283.             authdict = generate_response(chaldict, request_uri, self.auth_user, self.auth_pass, method = 'POST')
  284.             headers = {
  285.                 'Authorization': build_authorization_arg(authdict),
  286.                 'Expect': '100-continue' }
  287.             self.SendSOAPData(soapdata, url, soapaction, headers, **kw)
  288.             return None
  289.         
  290.         raise RuntimeError, 'Client expecting digest authorization challenge.'
  291.  
  292.     
  293.     def ReceiveRaw(self, **kw):
  294.         if self.data:
  295.             return self.data
  296.         
  297.         trace = self.trace
  298.         while None:
  299.             response = self.h.getresponse()
  300.             (self.reply_code, self.reply_msg, self.reply_headers, self.data) = (response.status, response.reason, response.msg, response.read())
  301.             if trace:
  302.                 print >>trace, '_' * 33, time.ctime(time.time()), 'RESPONSE:'
  303.                 for i in (self.reply_code, self.reply_msg):
  304.                     print >>trace, str(i)
  305.                 
  306.                 print >>trace, '-------'
  307.                 print >>trace, str(self.reply_headers)
  308.                 print >>trace, self.data
  309.             
  310.             saved = None
  311.             for d in response.msg.getallmatchingheaders('set-cookie'):
  312.                 if d[0] in (' ', '\t'):
  313.                     saved += d.strip()
  314.                     continue
  315.                 if saved:
  316.                     self.cookies.load(saved)
  317.                 
  318.                 saved = d.strip()
  319.             
  320.             if saved:
  321.                 self.cookies.load(saved)
  322.             
  323.             if response.status == 401:
  324.                 if not callable(self.http_callbacks.get(response.status, None)):
  325.                     raise RuntimeError, 'HTTP Digest Authorization Failed'
  326.                 
  327.                 self.http_callbacks[response.status](response)
  328.                 continue
  329.             
  330.             if response.status != 100:
  331.                 break
  332.             
  333.             self.h._HTTPConnection__state = httplib._CS_REQ_SENT
  334.             self.h._HTTPConnection__response = None
  335.             continue
  336.             return self.data
  337.  
  338.     
  339.     def IsSOAP(self):
  340.         if self.ps:
  341.             return 1
  342.         
  343.         self.ReceiveRaw()
  344.         mimetype = self.reply_headers.type
  345.         return mimetype == 'text/xml'
  346.  
  347.     
  348.     def ReceiveSOAP(self, readerclass = None, **kw):
  349.         if self.ps:
  350.             return self.ps
  351.         
  352.         if not self.IsSOAP():
  353.             raise TypeError('Response is "%s", not "text/xml"' % self.reply_headers.type)
  354.         
  355.         if len(self.data) == 0:
  356.             raise TypeError('Received empty response')
  357.         
  358.         if not readerclass:
  359.             pass
  360.         self.ps = ParsedSoap(self.data, readerclass = self.readerclass, encodingStyle = kw.get('encodingStyle'))
  361.         if self.sig_handler is not None:
  362.             self.sig_handler.verify(self.ps)
  363.         
  364.         return self.ps
  365.  
  366.     
  367.     def IsAFault(self):
  368.         self.ReceiveSOAP()
  369.         return self.ps.IsAFault()
  370.  
  371.     
  372.     def ReceiveFault(self, **kw):
  373.         self.ReceiveSOAP(**kw)
  374.         if not self.ps.IsAFault():
  375.             raise TypeError('Expected SOAP Fault not found')
  376.         
  377.         return FaultFromFaultMessage(self.ps)
  378.  
  379.     
  380.     def Receive(self, replytype, **kw):
  381.         self.ReceiveSOAP(**kw)
  382.         if self.ps.IsAFault():
  383.             msg = FaultFromFaultMessage(self.ps)
  384.             raise FaultException(msg)
  385.         
  386.         tc = replytype
  387.         if hasattr(replytype, 'typecode'):
  388.             tc = replytype.typecode
  389.         
  390.         reply = self.ps.Parse(tc)
  391.         if self.address is not None:
  392.             self.address.checkResponse(self.ps, kw.get('wsaction'))
  393.         
  394.         return reply
  395.  
  396.     
  397.     def __repr__(self):
  398.         return '<%s instance %s>' % (self.__class__.__name__, _get_idstr(self))
  399.  
  400.  
  401.  
  402. class Binding(_Binding):
  403.     gettypecode = staticmethod((lambda mod, e: getattr(mod, str(e.localName)).typecode))
  404.     logger = _GetLogger('ZSI.client.Binding')
  405.     
  406.     def __init__(self, url, namespace = None, typesmodule = None, **kw):
  407.         self.typesmodule = typesmodule
  408.         self.namespace = namespace
  409.         _Binding.__init__(self, url = url, **kw)
  410.  
  411.     
  412.     def __getattr__(self, name):
  413.         if name[:2] == '__' and len(name) > 5 and name[-2:] == '__':
  414.             if hasattr(self, name):
  415.                 return getattr(self, name)
  416.             
  417.             return getattr(self.__class__, name)
  418.         
  419.         return _Caller(self, name, self.namespace)
  420.  
  421.     
  422.     def __parse_child(self, node):
  423.         
  424.         try:
  425.             tc = self.gettypecode(self.typesmodule, node)
  426.         except:
  427.             self.logger.debug('didnt find typecode for "%s" in typesmodule: %s', node.localName, self.typesmodule)
  428.             tc = TC.Any(aslist = 1)
  429.             return tc.parse(node, self.ps)
  430.  
  431.         self.logger.debug('parse child with typecode : %s', tc)
  432.         
  433.         try:
  434.             return tc.parse(node, self.ps)
  435.         except Exception:
  436.             self.logger.debug('parse failed try Any : %s', tc)
  437.  
  438.         tc = TC.Any(aslist = 1)
  439.         return tc.parse(node, self.ps)
  440.  
  441.     
  442.     def Receive(self, replytype, **kw):
  443.         self.ReceiveSOAP(**kw)
  444.         ps = self.ps
  445.         tp = _find_type(ps.body_root)
  446.         if not type(tp) in (tuple, list) or tp[1] == 'Array':
  447.             pass
  448.         isarray = _find_arraytype(ps.body_root)
  449.         if self.typesmodule is None or isarray:
  450.             return _Binding.Receive(self, replytype, **kw)
  451.         
  452.         if ps.IsAFault():
  453.             msg = FaultFromFaultMessage(ps)
  454.             raise FaultException(msg)
  455.         
  456.         tc = replytype
  457.         if hasattr(replytype, 'typecode'):
  458.             tc = replytype.typecode
  459.         
  460.         reply = { }
  461.         for elt in _child_elements(ps.body_root):
  462.             name = str(elt.localName)
  463.             reply[name] = self._Binding__parse_child(elt)
  464.         
  465.         if self.address is not None:
  466.             self.address.checkResponse(ps, kw.get('wsaction'))
  467.         
  468.         return reply
  469.  
  470.  
  471.  
  472. class NamedParamBinding(Binding):
  473.     logger = _GetLogger('ZSI.client.Binding')
  474.     
  475.     def __getattr__(self, name):
  476.         if name[:2] == '__' and len(name) > 5 and name[-2:] == '__':
  477.             if hasattr(self, name):
  478.                 return getattr(self, name)
  479.             
  480.             return getattr(self.__class__, name)
  481.         
  482.         return _NamedParamCaller(self, name, self.namespace)
  483.  
  484.  
  485. if __name__ == '__main__':
  486.     print _copyright
  487.  
  488.